package com.cema.manage.project.manage.users.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cema.manage.project.enums.MoneyTypeEnum;
import com.cema.manage.project.enums.RedisEnum;
import com.cema.manage.project.enums.ToExamineEnum;
import com.cema.manage.project.enums.UserStatusEnum;
import com.cema.manage.project.manage.rewardRecord.domain.RewardRecord;
import com.cema.manage.project.manage.rewardRecord.service.IRewardRecordService;
import com.cema.manage.project.manage.users.domain.Users;
import com.cema.manage.project.manage.users.mapper.UsersMapper;
import com.cema.manage.project.system.user.domain.User;
import com.cema.manage.redis.RedisService;
import org.springframework.stereotype.Service;
import sun.net.TelnetOutputStream;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户账号 服务层实现
 *
 * @author reasahi
 * @date 2024-07-08
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Resource
    private IRewardRecordService rewardRecordService;

    @Resource
    private RedisService redisService;

    @Resource
    private UsersMapper usersMapper;

    @Override
    public void setStatus(Users users) {
        Users redisUser = (Users) redisService.get(users.getOpenid()+users.getDeviceId());
        if (ObjectUtil.isNull(redisUser)) {
            return;
        }
        //更新用户状态
        Users upUsers = new Users();
        upUsers.setId(users.getId());
        upUsers.setStatus(users.getStatus());
        usersMapper.updateById(upUsers);
        //重新更新缓存
        redisUser.setStatus(users.getStatus());
        redisService.set(users.getOpenid()+users.getDeviceId(), redisUser);
    }

    @Override
    public Integer updateKickback(Integer userId) {
        return usersMapper.updateKickback(userId);
    }

    @Override
    public Integer updateUsParentId(Integer userId) {
        return usersMapper.updateUsParentId(userId);
    }

    @Override
    public void updateMoneyExtensionRedEnvelope(Integer userId, Integer money,String uvChannel) {
        Users parentUsers = selectById(userId);
        if (ObjectUtil.isNull(parentUsers)) {
            return;
        }
        String ppc = (String) redisService.get(RedisEnum.PROXY_PROMOTION_COMMISSION.getKey()+uvChannel);
        if (StrUtil.isNotEmpty(ppc)) {
            Users usersUpdate = new Users();
            usersUpdate.setId(parentUsers.getId());
            int moneySum = Integer.parseInt(ppc) + parentUsers.getMoneyExtensionRedEnvelope();
            usersUpdate.setMoneyExtensionRedEnvelope(moneySum);
            updateById(usersUpdate);
            RewardRecord rewardRecord = new RewardRecord();
            rewardRecord.setUsId(parentUsers.getId());
            rewardRecord.setRrMoney(Integer.parseInt(ppc));
            rewardRecord.setUsNickname(parentUsers.getNickname());
            rewardRecord.setRrSourceType(3);
            rewardRecord.setRrType(MoneyTypeEnum.MONEY_EXTENSION_RED_ENVELOPE.getValue());
            rewardRecordService.insert(rewardRecord);
        }

    }

    @Override
    public Map<String, Object> toProxyStatistics(Integer usId) {
        //比例
        int proportion = 10000;
        //获取用户
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("us_parent_id", usId);
        entityWrapper.eq("status", UserStatusEnum.USER_STATUS_NORMAL.getValue());
        List<Users> usersList = selectList(entityWrapper);
        Map<String, Object> map = new HashMap<>(12);
        int apprenticeCount = 0;
        int apprenticeCountInsert = 0;
        int apprenticeCountActive = 0;
        if (ObjectUtil.isNotNull(usersList)) {
            apprenticeCount = usersList.size();
            List<Users> insertList = usersList.stream().filter(users -> DateUtil.isSameDay(users.getCreateTime(), new Date())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(insertList)) {
                apprenticeCountInsert = insertList.size();
            }
            List<Users> activeList = usersList.stream().filter(users -> DateUtil.isSameDay(users.getLoginTime(), new Date())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(activeList)) {
                apprenticeCountActive = activeList.size();
            }
        }
        //获取奖励
        EntityWrapper<RewardRecord> rewardEntity = new EntityWrapper<>();
        rewardEntity.eq("us_id", usId);
        rewardEntity.isNotNull("pus_id");
        List<RewardRecord> rewardRecordList = rewardRecordService.selectList(rewardEntity);
        BigDecimal income = BigDecimal.ZERO;
        BigDecimal incomeMGC = BigDecimal.ZERO;
        BigDecimal incomeMRP = BigDecimal.ZERO;
        BigDecimal incomeMonth = BigDecimal.ZERO;
        BigDecimal incomeMonthMGC = BigDecimal.ZERO;
        BigDecimal incomeMonthMRP = BigDecimal.ZERO;
        BigDecimal incomeToDay = BigDecimal.ZERO;
        BigDecimal incomeToDayMGC = BigDecimal.ZERO;
        BigDecimal incomeToDayMRP = BigDecimal.ZERO;
        if (ObjectUtil.isNotNull(rewardRecordList)) {
            int incomeSum = rewardRecordList.stream().mapToInt(RewardRecord::getRrMoney).sum();
            income = BigDecimal.valueOf(incomeSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
            int incomeMGCSum = rewardRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_COMMISSION_GOLD_COINS.getValue().equals(rewardRecord.getRrType())).mapToInt(RewardRecord::getRrMoney).sum();
            incomeMGC = BigDecimal.valueOf(incomeMGCSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
            int incomeMRPSum = rewardRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_COMMISSION_RED_ENVELOPE.getValue().equals(rewardRecord.getRrType())).mapToInt(RewardRecord::getRrMoney).sum();
            incomeMRP = BigDecimal.valueOf(incomeMRPSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
            //本月
            List<RewardRecord> monthRecordList = rewardRecordList.stream().filter(rewardRecord -> DateUtil.isSameMonth(rewardRecord.getCreateTime(), new Date())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(monthRecordList)) {
                int incomeMonthSum = monthRecordList.stream().mapToInt(RewardRecord::getRrMoney).sum();
                incomeMonth = BigDecimal.valueOf(incomeMonthSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
                int incomeMonthMGCSum = monthRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_COMMISSION_GOLD_COINS.getValue().equals(rewardRecord.getRrType())).mapToInt(RewardRecord::getRrMoney).sum();
                incomeMonthMGC = BigDecimal.valueOf(incomeMonthMGCSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
                int incomeMonthMRPSum = monthRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_COMMISSION_RED_ENVELOPE.getValue().equals(rewardRecord.getRrType())).mapToInt(RewardRecord::getRrMoney).sum();
                incomeMonthMRP = BigDecimal.valueOf(incomeMonthMRPSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
            }
            //今日
            List<RewardRecord> toDayRecordList = rewardRecordList.stream().filter(rewardRecord -> DateUtil.isSameDay(rewardRecord.getCreateTime(), new Date())).collect(Collectors.toList());
            if (ObjectUtil.isNotNull(toDayRecordList)) {
                int incomeToDaySum = toDayRecordList.stream().mapToInt(RewardRecord::getRrMoney).sum();
                incomeToDay = BigDecimal.valueOf(incomeToDaySum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
                int incomeToDayMGCCSum = toDayRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_COMMISSION_GOLD_COINS.getValue().equals(rewardRecord.getRrType())).mapToInt(RewardRecord::getRrMoney).sum();
                incomeToDayMGC = BigDecimal.valueOf(incomeToDayMGCCSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
                int incomeToDayMRPSum = toDayRecordList.stream().filter(rewardRecord -> MoneyTypeEnum.MONEY_COMMISSION_RED_ENVELOPE.getValue().equals(rewardRecord.getRrType())).mapToInt(RewardRecord::getRrMoney).sum();
                incomeToDayMRP = BigDecimal.valueOf(incomeToDayMRPSum).divide(BigDecimal.valueOf(proportion), 2, RoundingMode.DOWN);
            }
        }
        map.put("apprenticeCount", String.valueOf(apprenticeCount));
        map.put("apprenticeCountInsert", String.valueOf(apprenticeCountInsert));
        map.put("apprenticeCountActive", String.valueOf(apprenticeCountActive));
        map.put("income", String.valueOf(income));
        map.put("incomeMGC", String.valueOf(incomeMGC));
        map.put("incomeMRP", String.valueOf(incomeMRP));
        map.put("incomeMonth", String.valueOf(incomeMonth));
        map.put("incomeMonthMGC", String.valueOf(incomeMonthMGC));
        map.put("incomeMonthMRP", String.valueOf(incomeMonthMRP));
        map.put("incomeToDay", String.valueOf(incomeToDay));
        map.put("incomeToDayMGC", String.valueOf(incomeToDayMGC));
        map.put("incomeToDayMRP", String.valueOf(incomeToDayMRP));
        return map;
    }
}
